from flask import Blueprint, jsonify
from app.extensions import cors, csrf
from .resources.articles import ArticleAPI, ArticlesAPI, ArticleAuditAPI, ArticleSearchAPI
from .resources.attachment import AttachmentAPI
from .resources.category import CategoryAPI
from .resources.token import AuthTokenAPI
from .resources.users import UserAPI, UsersAPI, SmsAPI, UsersCompanyAPI
from .resources.companys import CompanysAPI
from .resources.report import ReportsAPI, ReportAPI


bp = Blueprint('api_v1', __name__)
cors.init_app(bp)
csrf.exempt(bp)


category_view = CategoryAPI.as_view('categorys')
bp.add_url_rule('/categorys', defaults={'id': None}, view_func=category_view, methods=['GET'])
bp.add_url_rule('/categorys/<int:id>', view_func=category_view, methods=['GET'])

# 单文章
bp.add_url_rule('/article/<int:id>', view_func=ArticleAPI.as_view('article'), methods=['GET', 'POST', 'DELETE'])
# 文章列表
bp.add_url_rule('/articles', view_func=ArticlesAPI.as_view('articles'), methods=['GET', 'POST'])

# 文章审核
bp.add_url_rule('/articles/audit/<int:id>', view_func=ArticleAuditAPI.as_view('articles/audit'), methods=['POST'])

# 文章查询
bp.add_url_rule('/articles/search', view_func=ArticleSearchAPI.as_view('articles/search'), methods=['GET'])

# 文章附件上传
bp.add_url_rule('/articles/attachment', view_func=AttachmentAPI.as_view('articles/attachment'), methods=['POST'])

# 文章附件删除
bp.add_url_rule('/articles/attachment/delete/<int:id>', view_func=AttachmentAPI.as_view('articles/attachment/delete'), methods=['DELETE'])

# 系统列表
bp.add_url_rule('/companys', view_func=CompanysAPI.as_view('companys'), methods=['GET'])

# 专报列表
bp.add_url_rule('/reports/<int:id>', view_func=ReportAPI.as_view('report'), methods=['GET'])
bp.add_url_rule('/reports', view_func=ReportsAPI.as_view('reports'), methods=['GET'])

# 获取用户信息
bp.add_url_rule('/user', view_func=UserAPI.as_view('user'), methods=['GET', 'POST'])
# 注册用户
bp.add_url_rule('/users', view_func=UsersAPI.as_view('users'), methods=['POST'])

# 修改用户单位
bp.add_url_rule('/user/company', view_func=UsersCompanyAPI.as_view('user/company'), methods=['POST'])

# 发送短信
bp.add_url_rule('/sms', view_func=SmsAPI.as_view('sms'), methods=['POST', 'PATCH'])

# 获取用户授权
bp.add_url_rule('/oauth/token', view_func=AuthTokenAPI.as_view('token'), methods=['POST'])


@bp.errorhandler(422)
def handle_validation_error(e):
    exc = e.exc
    return jsonify(errors=exc.messages), 422


@bp.errorhandler(403)
def handle_validation2_error(e):
    return jsonify(success=False, message='权限不够')
